package com.ukefu.webim.web.handler.apps.xiaoe;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.ansj.library.DicLibrary;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.util.Menu;
import com.ukefu.util.ai.DicSegment;
import com.ukefu.webim.service.es.TopicRepository;
import com.ukefu.webim.service.repository.WordsRepository;
import com.ukefu.webim.service.repository.WordsTypeRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.Topic;
import com.ukefu.webim.web.model.Words;
import com.ukefu.webim.web.model.WordsType;

@Controller
@RequestMapping("/apps/xiaoe")
public class XiaoEWordsController extends Handler{
	
	@Value("${web.upload-path}")
    private String path;
	
	@Value("${uk.im.server.port}")  
    private Integer port; 
	
	@Autowired
	private WordsTypeRepository wordsTypeRes ;
	
	@Autowired
	private TopicRepository topicRes ;
	
	@Autowired
	private WordsRepository wordsRes ;

	
    
    @RequestMapping("/words")
    @Menu(type = "xiaoe" , subtype = "words")
    public ModelAndView words(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type) throws IOException {
    	List<WordsType> wordsTypeList = wordsTypeRes.findByOrgi(super.getOrgi(request))  ; 
    	map.put("wordsTypeList", wordsTypeList);
    	WordsType ktype = null ;
    	if(!StringUtils.isBlank(type)){
    		for(WordsType wordsType : wordsTypeList){
    			if(wordsType.getId().equals(type)){
    				ktype = wordsType ;
    				break ;
    			}
    		}
    	}
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	File dicFile = null ;
    	if(ktype!=null){
    		map.put("curtype", ktype) ;
    		dicFile = getFile(ktype) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    		
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	List<Words> words = new ArrayList<Words>() ;
			for(String text : FileUtils.readLines(dicFile, "UTF-8")){
				if(!StringUtils.isBlank(text) && !text.startsWith("/")){
	    			String[] keys = text.split("/") ;
	    			words.add(new Words(keys[0] , keys.length >= 5 && !keys[4].equals("null") ? keys[4] : null , keys.length >= 4 &&  !keys[3].equals("null") ? keys[3] : null)) ;
				}
			}
			map.put("wordsList", words)  ;
    	}
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/words/index"));
    }
    
    @RequestMapping("/words/batcheck")
    @Menu(type = "xiaoe" , subtype = "words")
    public ModelAndView batcheck(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type) throws IOException {
    	List<WordsType> wordsTypeList = wordsTypeRes.findByOrgi(super.getOrgi(request))  ; 
    	map.put("wordsTypeList", wordsTypeList);
    	WordsType ktype = null ;
    	if(!StringUtils.isBlank(type)){
    		for(WordsType wordsType : wordsTypeList){
    			if(wordsType.getId().equals(type)){
    				ktype = wordsType ;
    				break ;
    			}
    		}
    	}
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	File dicFile = null ;
    	if(ktype!=null){
    		map.put("curtype", ktype) ;
    		dicFile = getFile(ktype) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    		
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	List<Words> words = new ArrayList<Words>() ;
			for(String text : FileUtils.readLines(dicFile, "UTF-8")){
				if(!StringUtils.isBlank(text) && !text.startsWith("/")){
	    			String[] keys = text.split("/") ;
	    			Words temp = new Words(keys[0] , keys.length >= 5 && !keys[4].equals("null") ? keys[4] : null , keys.length >= 4 &&  !keys[3].equals("null") ? keys[3] : null) ; 
	    			temp.setTokens(DicSegment.aisegment(temp.getKeyword()));
	    			if(temp.getTokens()!=null) {
	    				temp.setSame(temp.getTokens().length == 1);
	    			}
	    			if(temp.isSame() == false) {
	    				words.add(temp) ;
	    			}
 				}
			}
			map.put("wordsList", words)  ;
    	}
    	return request(super.createAppsTempletResponse("/apps/business/xiaoe/words/batcheck"));
    }
    
    @RequestMapping("/words/loadtopic")
    @Menu(type = "xiaoe" , subtype = "words")
    public ModelAndView loadtopic(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type) throws IOException {
    	List<WordsType> wordsTypeList = wordsTypeRes.findByOrgi(super.getOrgi(request))  ; 
    	map.put("wordsTypeList", wordsTypeList);
    	WordsType ktype = null ;
    	if(!StringUtils.isBlank(type)){
    		for(WordsType wordsType : wordsTypeList){
    			if(wordsType.getId().equals(type)){
    				ktype = wordsType ;
    				break ;
    			}
    		}
    	}
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	File dicFile = null ;
    	if(ktype!=null && "topic".equals(ktype.getCode())){
    		map.put("curtype", ktype) ;
    		dicFile = getFile(ktype) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}
    	List<String> ambiguityList = new ArrayList<String>();
    	File ambiguityFile = new File(path , "dic/ambiguity.dic") ;
    	if(ambiguityFile.exists()) {
    		ambiguityList = FileUtils.readLines(ambiguityFile) ;
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	Page<Topic> topicList = topicRes.findByOrgi(super.getOrgi(request),new PageRequest(0, 10000)) ;
	    	List<String> wordsList = new ArrayList<String>();
	    	for(Topic topic : topicList) {
	    		for(String temp : topic.getTitle().split("[\\pP\\p{Punct} ]") ) {
	    			temp = temp.replaceAll(" ", "") ;
					if(!StringUtils.isBlank(temp) && temp.length() > 1) {
						boolean found = false ;
						for(String ambi : ambiguityList) {
							if(ambi.indexOf(temp) == 0) {
								found = true ; break ;
							}
						}
						if(found == false) {
							wordsList.add(temp) ;
						}
					}
	    		}
	    		if(topic.getSilimar()!=null && topic.getSilimar().size() > 0) {
	    			for(String silimar : topic.getSilimar()) {
	    				for(String temp : silimar.split("[\\pP\\p{Punct} ]") ) {
	    					temp = temp.replaceAll(" ", "") ;
	    					if(!StringUtils.isBlank(temp) && temp.length() > 1) {
	    						boolean found = false ;
	    						for(String ambi : ambiguityList) {
	    							if(ambi.indexOf(temp) == 0) {
	    								found = true ; break ;
	    							}
	    						}
	    						if(found == false) {
	    							wordsList.add(temp) ;
	    						}
	    					}
	    				}
	    			}
	    		}
	    	}
	    	if(wordsList.size() > 0) {
	    		FileUtils.writeLines(dicFile,"UTF-8" , wordsList);
	    		DicLibrary.clear("topic");
	    		DicSegment.addWord(wordsList , "topic");
	    	}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html?type="+type));
    }
    
    @RequestMapping("/words/unloadtopic")
    @Menu(type = "xiaoe" , subtype = "words")
    public ModelAndView unloadtopic(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String type) throws IOException {
    	List<WordsType> wordsTypeList = wordsTypeRes.findByOrgi(super.getOrgi(request))  ; 
    	map.put("wordsTypeList", wordsTypeList);
    	WordsType ktype = null ;
    	if(!StringUtils.isBlank(type)){
    		for(WordsType wordsType : wordsTypeList){
    			if(wordsType.getId().equals(type)){
    				ktype = wordsType ;
    				break ;
    			}
    		}
    	}
    	if(!StringUtils.isBlank(q)){
    		map.put("q", q) ;
     	}
    	File dicFile = null ;
    	if(ktype!=null && "topic".equals(ktype.getCode())){
    		map.put("curtype", ktype) ;
    		dicFile = getFile(ktype) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	List<String> wordsList = new ArrayList<String>();
	    	for(String word : FileUtils.readLines(dicFile) ) {
	    		DicSegment.removeWord(word , "topic");
	    	}
	    	FileUtils.writeLines(dicFile,"UTF-8" , wordsList);
	    	DicLibrary.clear("topic");
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html?type="+type));
    }
    
    
    @RequestMapping("/words/delete")
    @Menu(type = "xiaoe" , subtype = "wordsdelete")
    public ModelAndView wordsdelete(HttpServletRequest request ,@Valid String word , @Valid String type) throws IOException {
    	String librarykey = "ukefu" ;
    	File dicFile = null ;
    	if(type!=null){
    		WordsType wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    		
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	List<String> words = FileUtils.readLines(dicFile, "UTF-8") ;
			for(int i =0 ;i<words.size() ; ){
				String text = words.get(i) ;
				if(!StringUtils.isBlank(text)){
	    			if(text.substring(0, text.indexOf("/")>0?text.indexOf("/"):text.length()).equals(word)){
	    				words.remove(i) ;
	    				continue ;
	    			}
				}else{
					words.remove(i) ;
    				continue ;
				}
				i++ ;
			}
			FileUtils.writeLines(dicFile,"UTF-8" , words);
			/**
			 * 同时删除 词库里 的词条
			 */
			DicSegment.removeWord(word,librarykey);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html?type="+type));
    }
    
    private File getFile(WordsType ktype) {
    	File dicFile = null ;
    	if("ambiguity".equals(ktype.getCode())) {
			dicFile = new File(path , "dic/ambiguity.dic") ;
		}else if("topic".equals(ktype.getCode())) {
			dicFile = new File(path , "dic/topic.dic") ;
		}else if("taboo".equals(ktype.getCode())) {
			dicFile = new File(path , "dic/ukefu-taboo"+ktype.getId()+".dic") ;
		}else {
			dicFile = new File(path , "dic/ukefu-"+ktype.getId()+".dic") ;
		}
    	return dicFile ;
    }
    
    private String getName(WordsType ktype) {
    	String name = "ukefu" ;
    	if("ambiguity".equals(ktype.getCode())) {
    		name = "ambiguity";
		}else if("topic".equals(ktype.getCode())) {
    		name = "topic";
		}else if("taboo".equals(ktype.getCode())) {
    		name = "taboo"+ktype.getId();
		}
    	return name ;
    }
    
    @RequestMapping("/words/batdelete")
    @Menu(type = "xiaoe" , subtype = "batdelete")
    public ModelAndView batdelete(HttpServletRequest request ,@Valid String word , @Valid String type) throws IOException {
    	String librarykey = "ukefu" ;
    	File dicFile = null ;
    	if(!StringUtils.isBlank(type)){
    		WordsType wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    		
    	}
    	if(dicFile!=null && dicFile.exists()){
	    	List<String> words = FileUtils.readLines(dicFile, "UTF-8") ;
			for(int i =0 ;i<words.size() ; ){
				String text = words.get(i) ;
				if(!StringUtils.isBlank(text)){
	    			if(word.indexOf(text.substring(0, text.indexOf("/")>0?text.indexOf("/"):text.length())) >= 0){
	    				words.remove(i) ;
	    				continue ;
	    			}
				}else{
					words.remove(i) ;
    				continue ;
				}
				i++ ;
			}
			FileUtils.writeLines(dicFile,"UTF-8" , words);
			/**
			 * 同时删除 词库里 的词条
			 */
			for(String w : word.split(",")) {
				DicSegment.removeWord(w,librarykey);
			}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html?type="+type));
    }
    
    @RequestMapping("/words/type/add")
    @Menu(type = "xiaoe" , subtype = "wordstypeadd")
    public ModelAndView wordstypeadd(ModelMap map , HttpServletRequest request ) {
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/words/addtype"));
    }
    
    @RequestMapping("/words/type/save")
    @Menu(type = "xiaoe" , subtype = "wordstypesave")
    public ModelAndView wordstypesave(HttpServletRequest request ,@Valid WordsType type) {
    	int tempTypeCount = wordsTypeRes.countByNameAndOrgi(type.getName(), super.getOrgi(request)) ;
    	if(tempTypeCount == 0){
    		type.setOrgi(super.getOrgi(request));
    		type.setCreatetime(new Date());
    		type.setUpdatetime(new Date());
    		type.setCreater(super.getUser(request).getId());
    		wordsTypeRes.save(type) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"));
    }
    
    @RequestMapping("/words/type/edit")
    @Menu(type = "xiaoe" , subtype = "wordstypeedit")
    public ModelAndView wordstypeedit(ModelMap map , HttpServletRequest request, @Valid String type ) {
    	map.put("wordsType", wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request))) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/words/edittype"));
    }
    
    @RequestMapping("/words/type/update")
    @Menu(type = "xiaoe" , subtype = "wordstypeupdate")
    public ModelAndView wordstypeupdate(HttpServletRequest request ,@Valid WordsType type) {
    	int tempTypeCount = wordsTypeRes.countByNameAndOrgi(type.getName(), super.getOrgi(request)) ;
    	if(tempTypeCount == 0){
    		WordsType temp = wordsTypeRes.findByIdAndOrgi(type.getId(), super.getOrgi(request)) ;
    		temp.setName(type.getName());
    		wordsTypeRes.save(temp) ;
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html?type="+type.getId()));
    }
    
    @RequestMapping("/words/type/delete")
    @Menu(type = "xiaoe" , subtype = "wordsdelete")
    public ModelAndView wordstypedelete(HttpServletRequest request ,@Valid String id , @Valid String type) throws IOException {
    	File dicFile = null ;
    	String librarykey = "ukefu";
    	if(type!=null){
    		WordsType wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    		wordsTypeRes.delete(wordsType);
    		DicSegment.removeLibrary(librarykey);
    	}
    	if(dicFile.length() > 0){
    		
    		List<String> words = FileUtils.readLines(dicFile, "UTF-8") ;
			for(int i =0 ;i<words.size() ; ){
				String text = words.get(i) ;
				if(StringUtils.isBlank(text)){
					words.remove(i) ;
    				continue ;
				}
				i++ ;
			}
			dicFile.delete();
	    	dicFile = new File(path , "dic/ukefu.dic") ;
			if(!dicFile.getParentFile().exists()){
				dicFile.getParentFile().mkdirs();
			}
			if(!dicFile.exists()){
				dicFile.createNewFile();
			}
			
			FileUtils.writeLines(dicFile,"UTF-8" , words , true);
			DicSegment.addWord(words, "ukefu");
    	}else {
    		dicFile.delete();
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"));
    }
    

    @RequestMapping("/words/add")
    @Menu(type = "xiaoe" , subtype = "wordsadd")
    public ModelAndView wordsadd(ModelMap map , HttpServletRequest request , @Valid String type) {
    	map.put("type", type);
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/words/add"));
    }
    
    @RequestMapping("/words/save")
    @Menu(type = "xiaoe" , subtype = "knowledgesave")
    public ModelAndView wordssave(HttpServletRequest request ,@Valid Words words , @Valid String type) throws IOException {
    	String librarykey = "ukefu" ;
    	File dicFile = null ;
    	if(!StringUtils.isBlank(type)){
    		WordsType wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}
    	if(dicFile!=null && dicFile.exists()){
    		List<String> lines = new ArrayList<String>();
    		if (!StringUtils.isBlank(words.getKeyword())) {
    			words.setKeyword(words.getKeyword().toLowerCase());
    			lines.add(words.getKeyword()) ;
			}
    		for(String word : words.getContent().split("[, ，:；;\\n\t\\r ]")){
    			if(!StringUtils.isBlank(word)){
    				boolean in = false ;
    				for(String w : lines) {
    					if(w.equals(word)) {
    						in = true ; break ;
    					}
    				}
    				if(in == false) {
    					lines.add(word) ;
    				}
    			}
    		}
    		FileUtils.writeLines(dicFile, "UTF-8" , lines, true);
    		DicSegment.addWord(lines,librarykey);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    
    @RequestMapping("/words/batadd")
    @Menu(type = "xiaoe" , subtype = "wordsbatadd")
    public ModelAndView wordsbatadd(ModelMap map , HttpServletRequest request , @Valid String type) {
    	map.put("type", type);
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/words/batadd"));
    }
    
    @RequestMapping("/words/edit")
    @Menu(type = "xiaoe" , subtype = "wordsbatedit")
    public ModelAndView wordsbatedit(ModelMap map , HttpServletRequest request , @Valid String word, @Valid String type) {
    	map.put("type", type);
    	WordsType wordsType = null ;
    	if(!StringUtils.isBlank(type)){
    		wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    	}
    	if(wordsType!=null && "ambiguity".equals(wordsType.getCode())) {
    		String[] temp = word.split("\t") ;
    		StringBuffer strb = new StringBuffer();
    		for(int i=0 ; i<temp.length ; i++) {
    			if(strb.length() > 0) {
					strb.append(" ") ;
				}
				strb.append(temp[i]) ;
    		}
    		map.put("word", strb.toString());
    		map.put("oldword", word);
    	}else {
    		map.put("word", word);
    	}
    	return request(super.createRequestPageTempletResponse("/apps/business/xiaoe/words/edit"));
    }
    
    @RequestMapping("/words/update")
    @Menu(type = "xiaoe" , subtype = "knowledgebatupdate")
    public ModelAndView wordsbatupdate(HttpServletRequest request ,@Valid String word , @Valid String type, @Valid String oldword) throws IOException {
    	String librarykey = "ukefu" ; 
    	File dicFile = null ;
    	WordsType wordsType = null ;
    	if(!StringUtils.isBlank(type)){
    		wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}
    	boolean found = false ;
    	if(wordsType!=null && "ambiguity".equals(wordsType.getCode())) {
    		String[] words = word.split(" ") ;
    		if(words.length == 3 || words.length == 2) {
    			StringBuffer strb = new StringBuffer();
    			for(int i=0 ; i<words.length ; i++) {
    				if(strb.length() > 0) {
    					strb.append("\t") ;
    				}
    				strb.append(words[i]) ;
    			}
    			word = strb.toString() ;
    		}else {
    			word = null ;
    		}
    	}
    	if(dicFile!=null && dicFile.exists() && !StringUtils.isBlank(word)){
    		word = word.toLowerCase();
	    	List<String> words = FileUtils.readLines(dicFile, "UTF-8") ;
			for(int i =0 ;i<words.size() ; ){
				String text = words.get(i) ;
				if(!StringUtils.isBlank(text)){
					String temp = text.substring(0, text.indexOf("/")>0?text.indexOf("/"):text.length()) ;
					if(temp.equals(word)) {
						found = true ;
					}else if(!StringUtils.isBlank(oldword) && temp.equals(java.net.URLDecoder.decode(oldword, "UTF-8"))){
	    				words.set(i, word) ;
	    				continue ;
	    			}
				}else{
					words.remove(i) ;
    				continue ;
				}
				i++ ;
			}
			/**
			 * 同时删除 词库里 的词条
			 */
			if(wordsType!=null && "ambiguity".equals(wordsType.getCode())) {
				FileUtils.writeLines(dicFile,"UTF-8" , words);
				DicLibrary.reload("ambiguity");
			}else {
				if(!word.equals(oldword)) {
					DicSegment.removeWord(oldword,librarykey);
				}
				if(found == false) {
					words.add(word) ;
					ArrayList<String> newWordList = new ArrayList<String>();
					newWordList.add(word) ;
					DicSegment.addWord(newWordList,librarykey);
				}
				FileUtils.writeLines(dicFile,"UTF-8" , words);
			}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    @RequestMapping("/words/batsave")
    @Menu(type = "xiaoe" , subtype = "knowledgebatsave")
    public ModelAndView wordsbatsave(HttpServletRequest request ,@Valid Words words , @Valid String type) throws IOException {
    	String librarykey = "ukefu" ; 
    	File dicFile = null ;
    	WordsType wordsType = null ;
    	if(!StringUtils.isBlank(type)){
    		wordsType = wordsTypeRes.findByIdAndOrgi(type,super.getOrgi(request)) ;
    		librarykey = getName(wordsType);
    		dicFile = getFile(wordsType) ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}else{
    		dicFile = new File(path , "dic/ukefu.dic") ;
    		if(!dicFile.getParentFile().exists()){
    			dicFile.getParentFile().mkdirs();
    		}
    		if(!dicFile.exists()){
    			dicFile.createNewFile();
    		}
    	}
    	List<String> lines = new ArrayList<String>();
    	if(!StringUtils.isBlank(words.getContent())){
    		words.setContent(words.getContent().toLowerCase());
    		Map<String,Boolean> wordsMap = new HashMap<String,Boolean>() ;
    		if(dicFile!=null && dicFile.exists()){
    			for(String text : FileUtils.readLines(dicFile, "UTF-8")){
    				if(!StringUtils.isBlank(text) && !text.startsWith("/")){
    	    			String[] keys = text.split("/") ;
    	    			wordsMap.put(keys[0], true) ;
    				}
    			}
        	}
    		if(wordsType!=null && "ambiguity".equals(wordsType.getCode())) {
    			for(String word : words.getContent().split("[,，:；;\\n\t]")){
    				String[] temp = word.split(" ") ;
    	    		if(temp.length == 3) {
    	    			word = temp[0]+"\t"+temp[1] + "\t"+temp[2] ;
    	    		}else if(temp.length == 2) {
    	    			word = temp[0]+"\t"+temp[1];
    	    		}else {
    	    			word = null ;
    	    		}
	    			if(!StringUtils.isBlank(word) && wordsMap.get(word)==null){
	    				lines.add(word) ;
	    			}
	    		}
    		}else {
	    		for(String word : words.getContent().split("[, ，:；;\\n\t ]")){
	    			if(!StringUtils.isBlank(word) && wordsMap.get(word)==null){
	    				lines.add(word.replaceAll(" ", "")) ;
	    			}
	    		}
	    		
    		}
    		if(lines.size() > 0) {
        		DicSegment.addWord(lines,librarykey);
        	}
    		if(dicFile!=null && dicFile.exists()){
        		FileUtils.writeLines(dicFile , "UTF-8",lines, true);
        	}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
    
    @RequestMapping("/words/reload")
    @Menu(type = "xiaoe" , subtype = "wordsreload")
    public ModelAndView wordsreload(ModelMap map , HttpServletRequest request , @Valid String type) throws IOException {
    	List<Words> wordsList = wordsRes.findByOrgi(super.getOrgi(request)) ;
		DicSegment.loadDic(new File(path , "dic").getAbsolutePath(),wordsList);
    	return request(super.createRequestPageTempletResponse("redirect:/apps/xiaoe/words.html"+(!StringUtils.isBlank(type) ? "?type="+type : "")));
    }
}